import sys

from PyQt6.QtCore import Qt, QRect, QPoint, QTimer, QTime, QDate
from PyQt6.QtGui import QPainter, QColor, QFont, QPolygon
from PyQt6.QtWidgets import QApplication, QWidget


class MyWidget(QWidget):

    # 指针形状
    hourShape = QPolygon([QPoint(6, 10), QPoint(-6, 10), QPoint(0, -45)])
    minuteShape = QPolygon([QPoint(6, 10), QPoint(-6, 10), QPoint(0, -70)])
    # 指针颜色
    hourColor = QColor(0, 255, 0)
    minuteColor = QColor(0, 0, 255)
    secondColor = QColor(255, 0, 0)

    def __init__(self):
        super(MyWidget, self).__init__()
        self.setWindowTitle('QPainter 测试：时钟')
        self.resize(600, 360)
        # 计时器 每秒刷新
        timer = QTimer(self)
        timer.timeout.connect(self.update)
        timer.start(1000)

    def paintEvent(self, event):
        time = QTime.currentTime()
        date = QDate.currentDate()

        painter = QPainter()
        painter.begin(self)

        # 日期文本
        rect = QRect(195, 150, 230, 30)
        date_str = date.toString('yyyy年MM月dd日')
        painter.setFont(QFont('黑体', 24))
        painter.drawText(rect, Qt.AlignmentFlag.AlignCenter, date_str)

        # 准备绘制时钟
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        side = min(self.width(), self.height())
        painter.translate(self.width() / 2, self.height() / 2)
        painter.scale(side / 200.0, side / 200.0)

        # 绘制刻度
        painter.setPen(MyWidget.hourColor)
        for i in range(12):
            painter.drawLine(88, 0, 96, 0)
            painter.rotate(30.0)
        painter.setPen(MyWidget.minuteColor)
        for j in range(600):
            if j % 5 != 0:
                painter.drawLine(94, 0, 96, 00)
                painter.rotate(6.0)

        # 绘制指针
        # 时针
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(MyWidget.hourColor)
        painter.save()
        painter.rotate(30.0 * ((time.hour() + time.minute()) / 60.0))
        painter.drawPolygon(MyWidget.hourShape)
        # 分针
        painter.restore()
        painter.setBrush(MyWidget.minuteColor)
        painter.rotate(6.0 * ((time.hour() + time.minute()) / 60.0))
        painter.drawPolygon(MyWidget.minuteShape)
        # 秒针
        painter.restore()
        painter.setBrush(MyWidget.secondColor)
        painter.drawEllipse(-4, -4, 8, 8)
        painter.save()
        painter.rotate(6.0 * time.second())
        painter.drawRoundedRect(-1, -1, 80, 2, 2, 2)
        painter.restore()

        painter.end()


if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWidget()
    window.show()
    sys.exit(app.exec())
